import './index.less';

import {inject, observer} from 'mobx-react';
import {
    WeaDialog,
    WeaPopoverHrm,
    WeaProgress,
    WeaTab,
    WeaMoreButton,
    WeaRightMenu,
    WeaLocaleProvider,
    WeaHelpfulTip
} from 'ecCom';
import {Button, Col, Row} from 'antd';
import {WeaTableNew} from "comsMobx";
import isEqual from 'lodash/isEqual';
import * as mobx from 'mobx';
import isEmpty from 'lodash/isEmpty';
import {Condition, getAdButtons} from './Condition';
import parseInt from 'lodash/parseInt';

const getLabel = WeaLocaleProvider.getLabel;

const WeaTable = WeaTableNew.WeaTable;

/***
 * 需求
 * dialogtitle
 * searchForm
 * tabs
 * tablestroe
 * rowClick
 * bottomBtns
 *
 */

@inject("flowReportDetailStore")
@observer
export default class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            height: 510
        }
        const {flowReportDetailStore} = props;
        flowReportDetailStore.loadCondition();
    }

    componentWillReceiveProps(nextProps) {
        const flag = isEqual(mobx.toJS(this.props.dataParams), mobx.toJS(nextProps.dataParams));
        if ((this.props.modalVisible !== nextProps.modalVisible || !flag) && nextProps.modalVisible) {
            const {flowReportDetailStore = {}, dataParams = {}, needAdvacnceSearch = false} = nextProps;
            const {setNeedAdvacnceSearch, doSearch, goTnto} = flowReportDetailStore;
            setNeedAdvacnceSearch(needAdvacnceSearch);
            doSearch({...dataParams, baseSearch: ''});
            goTnto(nextProps);
        }
        //关闭
        if (!nextProps.modalVisible) {
            const {flowReportDetailStore = {}} = nextProps;
            const {goTnto} = flowReportDetailStore;
            goTnto(nextProps);
        }
    }

    componentWillUnmount() {
        const {exportExcel} = this.props.flowReportDetailStore;
        exportExcel && exportExcel(false);
    }

    render() {
        const {height} = this.state;
        const {flowReportDetailStore} = this.props;
        const {versionTabs = [],currentProps = {}, pathProps, tableStore, dataKey, selectTabKey, queryParams = {}, loading = false, exportExcelUrl = '', needAdvacnceSearch = false, form, showSearchAd = false} = flowReportDetailStore;
        const {modalVisible = false, tabDatas = [], modaltitle = '', collectParams = {}} = currentProps;
        const {baseSearch = ''} = queryParams;
        const formParams = form.getFormParams() || {};
        let _modaltitle = modaltitle.replace(/<a.*?>/, '').replace('</a>', '');
        return (
            <div>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@9gmv9q`} visible={modalVisible}
                           title={_modaltitle}
                           icon={'icon-coms-workflow'}
                           iconBgcolor={'#0079DE'}
                           buttons={this.getBottomBtns()}
                           onCancel={this.closeModal.bind(this)}
                           style={{'width': 1000, 'height': 510}}
                           className={"wea-flow-report-detail-modal"}
                           onChangeHeight={this.changeHeight}
                >
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@ep87b9`} collectParams={collectParams} datas={this.getMoreBtns()}>
                        {needAdvacnceSearch ?
                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@70nywz`} datas={mobx.toJS(tabDatas)}
                                    keyParam={"key"}
                                    selectedKey={selectTabKey}
                                    onChange={this.doChangeTab.bind(this)}
                                    onSearch={v => {
                                        flowReportDetailStore.doSearch()
                                    }}
                                    onSearchChange={v => {
                                        flowReportDetailStore.setFormFields({requestname: {value: v}})
                                    }}
                                    searchType={['base', 'advanced']}
                                    searchsBaseValue={formParams.requestname}
                                    setShowSearchAd={bool => {
                                        flowReportDetailStore.setShowSearchAd(bool)
                                    }}
                                    hideSearchAd={() => flowReportDetailStore.setShowSearchAd(false)}
                                    showSearchAd={showSearchAd}
                                    buttonsAd={getAdButtons(flowReportDetailStore, this.props && this.props.ecId || '')}
                                    searchsAd={
                                        <Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@zu03gr`} flowReportDetailStore={flowReportDetailStore}/>
                                    }
                                    loading={loading}
                            />
                            :
                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@3my5ya`} datas={isEmpty(tabDatas) ? mobx.toJS(versionTabs) : mobx.toJS(tabDatas)}
                                    loading={loading}
                                    keyParam={"key"}
                                    selectedKey={selectTabKey}
                                    onSearchChange={this.doSearch.bind(this)}
                                    searchsBaseValue={baseSearch}
                                    searchType={['base']}
                                    onChange={this.doChangeTab.bind(this)}
                                    leftStyle = {{'width':800}}
                            />
                        }
                        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@2we8sg`} sessionkey={dataKey}
                                  comsWeaTableStore={tableStore}
                                  getColumns={this.getColumns.bind(this)}
                                  scroll={{y: height - 135}}
                                  rowKey={(record, index) => {
                                      return record.rowKeyspan||index;
                                  }}
                        />
                    </WeaRightMenu>
                </WeaDialog>
                <iframe ref="exportExcel" name="exportExcel" src={exportExcelUrl} style={{display: 'none'}}></iframe>
                <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@mmedr0`}/>
            </div>
        )
    }

    getBottomBtns() {
        const {flowReportDetailStore} = this.props;
        const {currentProps = {}} = flowReportDetailStore;
        const {collectParams = {}, bottomBtns = [], modaltitle = ''} = currentProps;
        let _modaltitle = modaltitle.replace(/<a.*?>/, '').replace('</a>', '');
        const btns = [];
        //人员办理时间分析表
        bottomBtns.map((btnInfo = {}, index) => {
            const {btnTitle = ''} = btnInfo;
            btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mfoy2d@${index}`} type="primary" size="large"
                              onClick={() => this.bottomBtnClickEvent(btnInfo)}>{btnTitle}</Button>);
        })
        btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@x7ak7m@doExportExcel`} type="primary" size="large"
                          onClick={this.doExportExcelEvent.bind(this, _modaltitle)}>{getLabel(28343, '导出Excel')}</Button>);
        btns.push(<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@7wl0ma@more`} datas={this.getMoreBtns()} collectParams={collectParams}/>);
        return btns;
    }

    getMoreBtns() {
        let moreBtns = [];
        const {flowReportDetailStore} = this.props;
        const {currentProps = {}, currentPropIndex = 0} = flowReportDetailStore;
        const {bottomBtns = [], modaltitle = ''} = currentProps;
        let _modaltitle = modaltitle.replace(/<a.*?>/, '').replace('</a>', '');
        bottomBtns.map((btnInfo = {}, index) => {
            const {btnTitle = '', icon = 'icon-coms-Workflow-o'} = btnInfo;
            moreBtns.push({
                key: `btn_${index}`,
                icon: <i className={icon}/>,
                content: btnTitle,
                onClick: (key) => {
                    this.bottomBtnClickEvent(btnInfo);
                }
            })
        });

        if (currentPropIndex > 1) {
            moreBtns.push({
                key: 'goBack',
                icon: <i className='icon-workflow-Right-menu-Return'/>,
                content: getLabel(1290, '返回'),
                onClick: (key) => this.goBack()
            });
        }

        moreBtns.push({
            key: 'export',
            icon: <i className='icon-coms-export'/>,
            content: getLabel(28343, '导出Excel'),
            onClick: (key) => this.doExportExcelEvent(_modaltitle)
        });
        return moreBtns;
    }

    doSearch(v) {
        const {flowReportDetailStore = {}} = this.props;
        flowReportDetailStore.doSearch && flowReportDetailStore.doSearch({baseSearch: v});
    }

    closeModal() {
        const {flowReportDetailStore} = this.props;
        const {currentProps = {}, clearFormFields} = flowReportDetailStore;
        const {tabDatas = [], closeModal} = currentProps;
        if (tabDatas.length > 0) {
            const {changeTab} = this.props.flowReportDetailStore;
            changeTab && changeTab(1);
        }
        this.props.flowReportDetailStore.clearTableStore();
        typeof closeModal === 'function' && closeModal();
        clearFormFields();
    }

    getColumns(columns) {
        const {flowReportDetailStore} = this.props;
        const {currentProps = {}} = flowReportDetailStore;
        const {isRowClick = false} = currentProps;
        let _this = this;
        let newColumns = columns.slice();
        const primayKeyField = this.getColumnPrimarkKeyField(newColumns);

        newColumns = newColumns.map(column => {
            if(column.dataIndex === "unoperators"){
                const title = (
                    <span>
                        <span title={column.title}>
                            { column.title }
                        </span>
                        {<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@79j6oy@${column.dataIndex}`} style={{ marginLeft: 5 }} title={getLabel(516719,"可在【个性化设置】中设置未操作者的显示类型")} placement="top" />}
                    </span>
                    )
                column.title = title;
            }
            let newColumn = column;
            newColumn.render = (text, record, index) => { //前端元素转义
                const columnDataIndex = newColumn.dataIndex;
                if (columnDataIndex === 'avgflowtimeInfo') {
                    newColumn.display = "false";
                    return "";
                }
                let valueSpan = record[columnDataIndex + "span"] !== undefined ? record[columnDataIndex + "span"] : record[columnDataIndex];
                if (columnDataIndex === 'avgflowtime') {
                    let avgflowtimeInfospan = record.avgflowtimeInfospan !== undefined ? record.avgflowtimeInfospan : record.avgflowtimeInfo;
                    return (
                        <div className={`chart-item ${isRowClick ? 'item-click' : ''}`}
                             onClick={() => _this.doRowClick(record, primayKeyField)}>
                            <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@oaw9mf@${columnDataIndex}`} style={{width: 200}} strokeWidth={10} strokeColor='#F60' percent={valueSpan} showInfo={false}/>
                            <span className="chart-value">{avgflowtimeInfospan}</span>
                        </div>
                    )
                }

                if (columnDataIndex === "num") {
                    let numInfo = record.num;
                    return (
                        <div className={`chart-item ${isRowClick ? 'item-click' : ''}`}
                             onClick={() => _this.doRowClick(record, primayKeyField)}>
                            <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@pm4ljx@${columnDataIndex}`} style={{width: 200}} strokeWidth={10} strokeColor='#F60' percent={valueSpan} showInfo={false}/>
                            <span className="chart-value">{numInfo}</span>
                        </div>
                    )
                }

                if (columnDataIndex === 'totalcount' || columnDataIndex === 'overtimecount') {
                    let totalCount = record[`${columnDataIndex}span`];
                    return (
                        <div className={'click-item'}
                             onClick={() => _this.doNumClick(record, primayKeyField, columnDataIndex)}>
                            <span>{parseInt(totalCount)}</span>
                        </div>
                    )
                }

                return (
                    <div className="wea-url" dangerouslySetInnerHTML={{__html: valueSpan}}/>
                )
            }
            return newColumn;
        });
        return newColumns
    }

    getColumnPrimarkKeyField(columns = []) {
        let primayKey = '';
        columns.map((column) => {
            const {isPrimarykey, dataIndex, dbField} = column;
            if ('true' == isPrimarykey && dataIndex == dbField) {
                primayKey = dataIndex;
            }
        })
        return primayKey;
    }

    doChangeTab(selectTabKey) {
        const {changeTab, doSearch} = this.props.flowReportDetailStore;
        changeTab && changeTab(selectTabKey);
        doSearch && doSearch();
    }

    doExportExcelEvent(filename = '') {
        const {exportExcel} = this.props.flowReportDetailStore;
        exportExcel && exportExcel(true, filename);
    }

    changeHeight = (height) => {
        this.setState({height});
    }

    doRowClick(record, primayKey) {
        const {flowReportDetailStore} = this.props;
        const {currentProps = {}} = flowReportDetailStore;
        const {updateModalPara, isRowClick, dataParams = {}, clickParams = {}} = currentProps;
        const {keyid = ''} = dataParams;
        if (isRowClick && typeof updateModalPara === 'function') {
            const key = record[primayKey];
            const title = record[`${primayKey}span`];
            const currentTime = new Date().getTime();
            updateModalPara({'keyid': key, title, 'parentKeyid': keyid, ...clickParams, currentTime})
        }
    }

    doNumClick(record, primayKey, columnDataIndex = '') {
        const {flowReportDetailStore} = this.props;
        const {currentProps = {}} = flowReportDetailStore;
        const {updateModalPara, isRowClick, dataParams = {}, clickParams = {}} = currentProps;
        const {keyid = ''} = dataParams;
        if (typeof updateModalPara === 'function') {
            const key = record[primayKey];
            const title = record[`${primayKey}span`];
            const currentTime = new Date().getTime();
            updateModalPara({
                'keyid': key,
                title,
                'parentKeyid': keyid,
                currentTime,
                columnDataIndex,
                ...clickParams,
                'clickNum': true
            })
        }
    }

    bottomBtnClickEvent(para = {}) {
        const {flowReportDetailStore} = this.props;
        const {currentProps = {}} = flowReportDetailStore;
        const {updateModalPara} = currentProps;
        if (typeof updateModalPara === 'function') {
            //为了渲染使用
            const currentTime = new Date().getTime();
            updateModalPara({...mobx.toJS(para), currentTime});
        }
    }

    goBack() {
        const {goBack} = this.props.flowReportDetailStore;
        goBack();
    }
}